<template>
  <div>
    <el-dialog
      :title="isEdit ? '编辑部门' : '新增部门' "
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" style="width:80%" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code" style="width:80%" placeholder="1-20个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
            <el-option v-for="obj in employeeList" :key="obj.id" :value="obj.username" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelFn">取 消</el-button>
        <el-button type="primary" @click="enterFn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeSimpleAPI, addDepartmentsAPI, getDepartDetailAPI, updateDepartmentsAPI } from '@/api'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    // 父级部门id
    parentId: {
      type: String,
      default: ''
    },
    isEdit: {
      type: Boolean
    },
    // 用于非重验证(全部的部门数据)
    originList: {
      type: Array,
      default: _ => [],
      require: true
    }
  },
  data() {
    const validateCode = (rules, value, callback) => {
      // 提取数组里code,形成一个只有code的数组方便下面使用includes
      let arr = this.originList.map(item => item.code)

      // 如果是编辑状态, 则将需要编辑的这一项排除在外
      if (this.isEdit) {
        // 从所有对象中,排除id为正在编辑的对象id,把其他的过滤收集处理,再重新映射
        arr = this.originList.filter(item => item.id !== this.parentId).map(item => item.code)
      }

      arr.includes(value) ? callback(new Error(`此部门编码${value}, 已经存在了`)) : callback()
    }

    const validateName = (rules, value, callback) => {
      let arr = this.originList.filter(item => item.pid === this.parentId).map(item => item.name)

      // 上面是新增,编辑要走这里重新取值
      if (this.isEdit) {
        const obj = this.originList.find(item => item.id === this.parentId)
        const pid = obj.pid
        arr = this.originList.filter(item => item.pid === pid && item.id !== this.parentId).map(item => item.name)
      }

      arr.includes(value) ? callback(new Error(`此部门名字${value}, 已经存在了`)) : callback()
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      employeeList: [], // 部门负责人列表
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '部门名称要求2-10个字符', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 20, message: '部门编码要求1-20个字符', trigger: 'blur' },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    dialogVisible() {
      if (this.dialogVisible === true) {
        this.getDepartDetailFn()
      }
    }
  },
  created() {
    this.getEmployeeFn()
  },
  methods: {
    handleClose(done) {
      // this.$confirm('确认关闭？')
      //   .then(_ => {
      //     done()
      //   })
      //   .catch(_ => {})
      this.$refs.deptForm.resetFields()
      done()
    },
    // 取消按钮
    cancelFn() {
      this.$refs.deptForm.resetFields()
      this.$emit('update:dialogVisible', false)
    },
    // 确认按钮
    async enterFn() {
      this.$refs.deptForm.validate(async valid => {
        if (valid) {
          if (this.isEdit === true) { // 编辑状态
            const res = await updateDepartmentsAPI({
              ...this.form,
              id: this.parentId
            })
            this.$message.success(res.message)
          } else { // 新增
            // console.log(this.parentId)
            const res = await addDepartmentsAPI({
              ...this.form,
              pid: this.parentId // 新增部门pid等于父级部门id
            })
            this.$message.success(res.message)
          }

          this.$emit('update:dialogVisible', false)
          this.$emit('resertList') // 让父级重新获取整个列表
        } else {
          this.$message.error('表单未通过校验')
        }
      })
      this.$refs.deptForm.resetFields()
    },
    async getEmployeeFn() {
      const res = await getEmployeeSimpleAPI()
      console.log(res)
      this.employeeList = res.data
    },
    // 请求某个部门的详细信息 -> 数据回显
    async getDepartDetailFn() {
      if (this.isEdit === true) {
        const res = await getDepartDetailAPI(this.parentId)
        this.form = res.data
        console.log(res)
      }
    }
  }
}
</script>

<style>

</style>
